<?php
    class AdminDthink_UserController extends Main_Controller_Action
    {
        public function init()
        {
            $this->loadTemplates('admin');
        }
        
        public function preDispatch()
        {
        	$auth = Zend_Auth::getInstance();
        	if((!$auth->hasIdentity()) || ($auth->getIdentity()->level != 0))
        	{
        		if($this->_request->getActionName() != 'login')
        		{
        			$this->_redirect('/admin-dthink/index/login');
        		}
        	}
        }
        
        public function indexAction()
        {
            $this->view->headTitle("Quản lý tài khoản");
            $user = new AdminDthink_Model_User();
            $auth = Zend_Auth::getInstance();
            $infoUser = $auth->getIdentity();
            $user_id = $infoUser->user_id;
            
            if($_POST['add'])
            {
                $this->_redirect('admin-dthink/user/create');
            }
            if($_POST['refresh'])
            {
                $this->_redirect('admin-dthink/user');
            }
            if($_POST['delete'])
            {
                $listId = $this->_request->getParam('check');
                $user->deleteUsers($listId);
                $this->_redirect('admin-dthink/user');
            }
            
            $list = $user->listUser($user_id);
            $paginator = Zend_Paginator::factory($list);
            $paginator->setItemCountPerPage(20);
            $paginator->setPageRange(5);
            $currentPage = $this->_request->getParam('page', 1);
            $paginator->setCurrentPageNumber($currentPage);
            
            $this->view->data = $paginator;
            $this->view->total = count($list);
        }
        
        public function createAction()
        {
            $this->view->headTitle("Thêm tài khoản mới");
            $user = new AdminDthink_Model_User();
            $product = new AdminDthink_Model_Product();
            
            if($this->_request->isPost())
            {
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                $avatar = $upload->getFileName('avatar', false);
                $filter = new Zend_Filter_StringTrim();
                $email = $filter->filter($this->_request->getParam('email'));
                $password = $this->_request->getParam('password');
                $rePassword = $this->_request->getParam('rePassword');
                $level = $this->_request->getParam('level');
                $fullname = $filter->filter($this->_request->getParam('fullname'));
                $gender = $this->_request->getParam('gender');
                $birthday = $this->_request->getParam('birthday');
                $flag = true;
                
                $validation = new AdminDthink_Form_ValidateUser();
                if($validation->validEmail($email))
                {
                    $this->view->emailValue = $email;
                }
                else
                {
                    $this->view->errorEmail = 'Địa chỉ email không hợp lệ';
                    $flag = false;
                }
                if($user->checkUser($email, '') > 0)
                {
                    $this->view->errorEmail = 'Địa chỉ email này đã tồn tại';
                    $flag = false;
                }
                if(!$validation->validPassword($password))
                {
                    $this->view->errorPassword = 'Mật khẩu yêu cầu từ 6-32 kí tự';
                    $flag = false;
                }
                if(!$validation->validPassword($rePassword))
                {
                    $this->view->errorRePassword = 'Mật khẩu yêu cầu từ 6-32 kí tự';
                    $flag = false;
                }
                if($validation->validFullname($fullname))
                {
                    $this->view->fullnameValue = $fullname;
                }
                else
                {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                if($birthday != '')
                {
                    if($validation->validBirthday($birthday))
                    {
                        $this->view->birthdayValue = $birthday;
                    }
                    else
                    {
                        $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (Ngày-Tháng-Năm)';
                        $flag = false;
                    }
                }
                
                if($flag == true)
                {
                    $birthday = $product->convertToMysql($birthday);
                    if($password == $rePassword)
                    {
                        if(!$validation->validAvatar($avatar))
                        {
                            if($level == '2')
                            {
                                $provider_id = $this->_request->getParam('provider_id');
                                $user->addUser($email, $password, 0, $fullname, $gender, $birthday, $level, $provider_id);
                            }
                            else
                            {
                                $user->addUser($email, $password, 0, $fullname, $gender, $birthday, $level, '');
                            }
                            $this->_redirect('admin-dthink/user');
                        }
                        else
                        {
                            $upload->addValidator('Size', false, 410000)
                                   ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                            if(!$upload->isValid())
            				{
            					$this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
            				}
                            else
                            {
                                preg_match('#\.([^\.]+)$#', $avatar, $matches);
        						$fileExtension  = $matches[1];
        						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;						
        						
        						$options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName,'overwrite'=>true);
        						$upload->addFilter('Rename',$options,'avatar');
        						$upload->receive('avatar');
        						
                                if($level == '2')
                                {
                                    $provider_id = $this->_request->getParam('provider_id');
                                    $user->addUser($email, $password, $newFileName, $fullname, $gender, $birthday, $level, $provider_id);
                                }
                                else
                                {
                                    $user->addUser($email, $password, $newFileName, $fullname, $gender, $birthday, $level, '');
                                }
        						$this->_redirect('admin-dthink/user');
                            }
                        }
                    }
                    else
                    {
                        $this->view->error = 'Mật khẩu không trùng khớp';
                    }
                }
            }
        }
        
        public function editAction()
        {
            $this->view->headTitle('Sửa thông tin tài khoản');
            $user_id = $this->_request->getParam('id');
            $user = new AdminDthink_Model_User();
            $product = new AdminDthink_Model_Product();
            $this->view->data = $user->getUserById($user_id);
            
            if($_POST['delImg'])
            {
				$update = $user->delImg($user_id);
				if($update)
				{
					if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
					{
						unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
					}
					$this->_redirect('admin-dthink/user');
				}
            }
            
            if($_POST['submit'])
            {
                $filter = new Zend_Filter_StringTrim();
                $password = $this->_request->getParam('password');
                $rePassword = $this->_request->getParam('rePassword');
                $email = $filter->filter($this->_request->getParam('email'));
                $level = $this->_request->getParam('level');
                $status = $this->_request->getParam('status');
                $fullname = $filter->filter($this->_request->getParam('fullname'));
                $gender = $this->_request->getParam('gender');
                $birthday = $this->_request->getParam('birthday');
                $flag = true;
                
                $validation = new AdminDthink_Form_ValidateUser();
                if(!$validation->validEmail($email))
                {
                    $this->view->errorEmail = 'Địa chỉ email không hợp lệ';
                    $flag = false;
                }
                if(!$validation->validFullname($fullname))
                {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                if($birthday != '')
                {
                    if(!$validation->validBirthday($birthday))
                    {
                        $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (Ngày-Tháng-Năm)';
                        $flag = false;
                    }
                }
                if($this->view->data['email'] != $email)
                {
                    if($user->checkUser($email, $user_id) > 0)
                    {
                        $this->view->errorEmail = 'Địa chỉ email này đã tồn tại';
                        $flag = false;
                    }
                }
                
                if($flag == true)
                {
                    $provider_id = $this->_request->getParam('provider_id');
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    $info = $upload->getFileInfo();
                    $avatar = $upload->getFileName('avatar', false);
                    
                    if(($password != '') or ($rePassword != ''))
                    {
                        if(!$validation->validPassword($password))
                        {
                            $this->view->errorPassword = 'Mật khẩu phải từ 6-32 kí tự';
                            $flag = false;
                        }
                        if(!$validation->validPassword($rePassword))
                        {
                            $this->view->errorRePassword = 'Mật khẩu phải từ 6-32 kí tự';
                            $flag = false;
                        }
                        if($password != $rePassword)
                        {
                            $this->view->error = 'Mật khẩu không trùng khớp';
                            $flag = false;
                        }
                        if($flag == true)
                        {
                            if(!$validation->validAvatar($avatar))
                            {
                                $birthday = $product->convertToMysql($birthday);
                                if($level == '2')
                                {
                                    $user->editUser($user_id, $email, $password, '', $fullname, $gender, $birthday, $level, $status, $provider_id);
                                }
                                else
                                {
                                    $user->editUser($user_id, $email, $password, '', $fullname, $gender, $birthday, $level, $status);
                                }
                                $this->_redirect('admin-dthink/user');
                            }
                            else
                            {
                                $upload->addValidator('Size', false, 410000)
                                       ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                                if(!$upload->isValid())
                				{
                					$this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
                				}
                                else
                                {
                                    preg_match('#\.([^\.]+)$#', $avatar, $matches);
            						$fileExtension  = $matches[1];
            						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
            						
            						$options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName,'overwrite'=>true);
            						$upload->addFilter('Rename',$options,'avatar');
            						$upload->receive('avatar');
            						
                                    if($level == '2')
                                    {
                                        $user->editUser($user_id, $email, $password, $newFileName, $fullname, $gender, $birthday, $level, $status, $provider_id);
                                    }
                                    else
                                    {
                                        $user->editUser($user_id, $email, $password, $newFileName, $fullname, $gender, $birthday, $level, $status);
                                    }
            						if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
            						{
                                        unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
            						}
            						$this->_redirect('admin-dthink/category');
                                }
                            }
                        }
                    }
                    else
                    {
                        $birthday = $product->convertToMysql($birthday);
                        if(!$validation->validAvatar($avatar))
                        {
                            if($level == '2')
                            {
                                $user->editUser($user_id, $email, '', '', $fullname, $gender, $birthday, $level, $status, $provider_id);
                            }
                            else
                            {
                                $user->editUser($user_id, $email, '', '', $fullname, $gender, $birthday, $level, $status);
                            }
                            $this->_redirect('admin-dthink/user');
                        }
                        else
                        {
                            $upload->addValidator('Size', false, 410000)
                                   ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                            if(!$upload->isValid())
              				{
           					    $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
            				}
                            else
                            {
                                preg_match('#\.([^\.]+)$#', $avatar, $matches);
          						$fileExtension  = $matches[1];
          						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
            						
          						$options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName,'overwrite'=>true);
          						$upload->addFilter('Rename',$options,'avatar');
          						$upload->receive('avatar');
          						
                                if($level == '2')
                                {
                                    $user->editUser($user_id, $email, '', $newFileName, $fullname, $gender, $birthday, $level, $status, $provider_id);
                                }
                                else
                                {
                                    $user->editUser($user_id, $email, '', $newFileName, $fullname, $gender, $birthday, $level, $status);
                                }
          						if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
          						{
                                    unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
          						}
          						$this->_redirect('admin-dthink/user');
                            }
                        }
                    }
                }
            }
        }
        
        public function deleteAction()
        {
            $user_id = $this->_request->getParam('id');
            $user = new AdminDthink_Model_User();
            $user->deleteUser($user_id);
            $this->_redirect('admin-dthink/user');
        }
        
        public function searchAction()
        {
            $this->view->headTitle('Tìm kiếm tài khoản');
            $filter = new Zend_Filter_StringTrim();
            $keyword = $filter->filter($this->_request->getParam('keyword'));
            $this->view->searchvalue = $keyword;
            $user = new AdminDthink_Model_User();
            $flag = true;
            
            if($this->_request->isPost())
			{				
				$validation = new AdminDthink_Form_ValidateUser();
				if($validation->validSearch($keyword))
				{
					$this->view->searchValue = $keyword;
				}
				else
				{
					$this->view->errorSearch = 'Bạn chưa nhập từ khóa';
					$result = $user->searchUser($keyword);
					$paginator = Zend_Paginator::factory($result);
					$paginator->setItemCountPerPage(20);
					$paginator->setPageRange(5);
					$currentPage = $this->_request->getParam('page', 1);
					$paginator->setCurrentPageNumber($currentPage);
						
					$this->view->total = count($result);
					$this->view->data = $paginator;
					$flag = false;
				}

				if($flag == true)
				{
					$result = $user->searchUser($keyword);
					$paginator = Zend_Paginator::factory($result);
					$paginator->setItemCountPerPage(20);
					$paginator->setPageRange(5);
					$currentPage = $this->_request->getParam('page', 1);
					$paginator->setCurrentPageNumber($currentPage);
						
					$this->view->total = count($result);
					$this->view->data = $paginator;
				}
			}
			
			if($_POST['add'])
			{
				$this->_redirect('admin-dthink/user/create');
			}
			if($_POST['refresh'])
			{
				$this->_redirect('admin-dthink/user');
			}
			if($_POST['delete'])
			{
				$listId = $this->_request->getParam('check');
				$result = $user->deleteUsers($listId);
				$this->_redirect('admin-dthink/user');
			}
			
			$validation = new AdminDthink_Form_ValidateUser();
			if($validation->validSearch($keyword))
			{
				$this->view->searchValue = $keyword;
			}
			else
			{
				$this->view->errorSearch = 'Bạn chưa nhập từ khóa';
				$result = $user->searchUser($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(20);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
						
				$this->view->total = count($result);
				$this->view->data = $paginator;
				$flag = false;
			}
			
			if($flag == true)
			{
				$result = $user->searchUser($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(20);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
				
				$this->view->total = count($result);
				$this->view->data = $paginator;
			}
        }
        
        public function profileAction()
        {
        	$this->view->headTitle('Thông tin tài khoản');
            $user = new AdminDthink_Model_User();
            $product = new AdminDthink_Model_Product();
            $auth = Zend_Auth::getInstance();
            $infoUser = $auth->getIdentity();
            $user_id = $infoUser->user_id;
            $this->view->data = $user->getUserById($user_id);
            
            if($_POST['delImg'])
            {
                $update = $user->delImg($user_id);
				if($update)
				{
					if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
					{
						unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
					}
					$this->view->error = 'Đã xóa ảnh thành công';
                    $this->view->data = $user->getUserById($user_id);
				}
            }
            
            if($_POST['submit'])
            {
                $filter = new Zend_Filter_StringTrim();
                $email = $this->view->data['email'];
                $fullname = $filter->filter($this->_request->getParam('fullname'));
                $birthday = $this->_request->getParam('birthday');
                $level = $this->_request->getParam('level');
                $status = $this->_request->getParam('status');
                $gender = $this->_request->getParam('gender');
                $flag = true;
                
                $validation = new AdminDthink_Form_ValidateUser();
                if(!$validation->validFullname($fullname))
                {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                if($birthday != '')
                {
                    if(!$validation->validBirthday($birthday))
                    {
                        $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (Ngày-Tháng-Năm)';
                        $flag = false;
                    }
                }
                
                if($flag == true)
                {
                    $birthday = $product->convertToMysql($birthday);
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    $info = $upload->getFileInfo();
                    $avatar = $upload->getFileName('avatar', false);
                    if(!$validation->validAvatar($avatar))
                    {
                        $user->editUser($user_id, $email, '', '', $fullname, $gender, $birthday, $level, $status);
                        $this->view->error = 'Đã sửa thành công';
                        $this->view->data = $user->getUserById($user_id);
                    }
                    else
                    {
                        $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid())
        				{
   					        $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
        				}
                        else
                        {
                            preg_match('#\.([^\.]+)$#', $avatar, $matches);
      						$fileExtension  = $matches[1];
      						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
            						
      						$options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName,'overwrite'=>true);
      						$upload->addFilter('Rename',$options,'avatar');
      						$upload->receive('avatar');
            						
      						$user->editUser($user_id, $email, '', $newFileName, $fullname, $gender, $birthday, $level, $status);
      						if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
      						{
                                unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
      						}
      						$this->view->error = 'Đã sửa thành công';
                            $this->view->data = $user->getUserById($user_id);
                        }
                    }
                }
            }
        }
        
        public function changepasswordAction()
        {
        	$this->view->headTitle('Thay đổi mật khẩu');
        	$user = new AdminDthink_Model_User();
        	$validation = new AdminDthink_Form_ValidateUser();
        	
        	if($this->_request->isPost())
        	{
        		$oldPassword = $this->_request->getParam('oldPassword');
        		$password = $this->_request->getParam('password');
        		$rePassword = $this->_request->getParam('rePassword');
        		$flag = true;
        		
        		if($validation->validPassword($oldPassword))
        		{
        			$this->view->oldPasswordValue = $oldPassword;
        		}
        		else
        		{
        			$this->view->errorOldPassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
        			$flag = false;
        		}
        		if($validation->validPassword($password))
        		{
        			$this->view->passwordValue = $password;
        		}
        		else
        		{
        			$this->view->errorPassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
        			$flag = false;
        		}
        		if($validation->validPassword($rePassword))
        		{
        			$this->view->rePasswordValue = $rePassword;
        		}
        		else 
        		{
        			$this->view->errorRePassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
        			$flag = false;
        		}
        		
        		if($flag == true)
        		{
        			$auth = Zend_Auth::getInstance();
        			$infoUser = $auth->getIdentity();
        			$user_id = $infoUser->user_id;
        			$checkPassword = $user->checkPassword($user_id, $oldPassword);
        			if($checkPassword)
        			{
        				if($password == $rePassword)
        				{
        					$result = $user->changePasswordUser($user_id, $password);
        					if($result)
        					{
        						$this->view->error = 'Đổi mật khẩu thành công';
        					}
        					else
        					{
        						$this->view->error = 'Có lỗi xảy ra';
        					}
        				}
        				else
        				{
        					$this->view->error = 'Mật khẩu mới không trùng khớp';
        				}
        			}
        			else 
        			{
        				$this->view->error = 'Mật khẩu không chính xác';
        			}
        		}
        	}
        }
    }
